package tree.test144;

import listbyorder.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/17 10:19
 */
public class Solution3 {

    // Morris遍历
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root != null) {
            TreeNode c1 = root;
            TreeNode c2;
            while (c1 != null) {
                c2 = c1.left;
                if (c2 != null) {
                    while (c2.right != null && c2.right != c1) {
                        c2 = c2.right;
                    }
                    if (c2.right == null) {
                        c2.right = c1;
                        res.add(c1.val);
                        c1 = c1.left;
                        continue;
                    }
                    if (c2.right == c1) {
                        c2.right = null;
                        c1 = c1.right;
                    }
                } else {
                    res.add(c1.val);
                    c1 = c1.right;
                }
            }
        }
        return res;
    }
}
